package com.indexingsystem.system.controller;


import com.indexingsystem.boss.Vo.*;
import com.indexingsystem.boss.common.PagedResult;
import com.indexingsystem.boss.common.ProgramLogsCommon;
import com.indexingsystem.boss.entity.IdxIndexingProductsCheck;
import com.indexingsystem.boss.entity.ProgramLogs;
import com.indexingsystem.boss.logback.LogCvt;
import com.indexingsystem.boss.utils.DateUtil;
import com.indexingsystem.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/IndexingSystem/Service")
public class IdxProductIndexingController {

    private ProgramLogs logs;

    @Resource
    private IProgramLogsService logsService;

    @Resource
    private IdxProductsThemeWordsService idxProductsThemeWordsService;

    @Resource
    private IdxExportIndexingProductService idxExportIndexingProductService;

    @Resource
    private IdxIndexingProductsCheckService idxIndexingProductsCheckService;

    @Resource
    private IdxTaskProductService idxTaskProductService;

    @Resource
    private IdxTaskService idxTaskService;

    /**
     * 5.24 产品标引结果导出
     * 如果发生报错，可能是因为数据表中缺少字段。
     *
     * @param reqVo
     * @return
     */
    //解决同步问题，修改测试。
    @RequestMapping(value = "/ExportIndexingThemeWords", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> exportIndexingThemeWords(@RequestBody ExportThemeWordsReqVo reqVo) {
        LogCvt.info("/Service/ExportIndexingThemeWords");
        Map<String, Object> result = new HashMap<>();
        String message = "操作失败";
        String result_code = "9999";
        String reason = "";
        if (null != reqVo) {
            System.out.println(reqVo.toString());
            try {
                if (StringUtils.isBlank(reqVo.getExportPath())) {
                    message = "导出路径不能为空！";
                } else if (StringUtils.isBlank(reqVo.getExportType())) {
                    message = "导出类型不能为空！";
                } else if (!reqVo.getExportType().toLowerCase().equals("excel") && !reqVo.getExportType().toLowerCase().equals("xml")) {
                    message = "导出类型不合法！";
                } else {
                    if (reqVo.getProductId() != null && reqVo.getProductId().size() > 0) {
                        if (reqVo.getTaskId() != null && reqVo.getTaskId().size() == 1) {
                            ExportThemeWordsReqVoSingle reqVoSingle = new ExportThemeWordsReqVoSingle();
                            reqVoSingle.setTaskId(Integer.parseInt(reqVo.getTaskId().get(0)));
                            reqVoSingle.setProductId(reqVo.getProductId());
                            reqVoSingle.setExportType(reqVo.getExportType());
                            if (reqVo.getThemeTableId() != null) {
                                reqVoSingle.setThemeTableId(reqVo.getThemeTableId());
                            }
                            String s = idxProductsThemeWordsService.exportProductIndexing(reqVo, reqVoSingle);

                            message = "操作成功！";
                            result_code = "0000";

                        } else {
                            message = "参数不合法！";
                        }
                    } else {
                        if (reqVo.getTaskId() == null || reqVo.getTaskId().size() < 1) {
                            List<String> topTaskIds = idxTaskService.getTopTaskIds();
                            reqVo.setTaskId(topTaskIds);
                        }
                        for (String id : reqVo.getTaskId()) {
                            ExportThemeWordsReqVoSingle reqVoSingle = new ExportThemeWordsReqVoSingle();
                            reqVoSingle.setTaskId(Integer.parseInt(id));
                            reqVoSingle.setThemeTableId(reqVo.getThemeTableId());
                            reqVoSingle.setExportType(reqVo.getExportType());
                            idxProductsThemeWordsService.exportProductIndexing(reqVo, reqVoSingle);
                        }

                        message = "操作成功！";
                        result_code = "0000";

                    }
                }

            } catch (Exception ex) {
                if (ex instanceof NumberFormatException) {
                    reason = "参数不合法！";
                } else {
                    reason = ex.getMessage();
                }
                LogCvt.error("产品标引结果导出失败，原因：" + reason);
                logs = ProgramLogsCommon.init();
                logs.setMessage("/Service/ExportIndexingThemeWords");
                logs.setLevel("1");
                logs.setLogger("ToDataBase");
                logs.setLogTime(DateUtil.parseFormatToDate(DateUtil.getCurTotalDate()));
                logs.setException(ex.toString());
                logsService.insertSelective(logs);

                message = "操作失败：" + reason;
            }
        } else {
            message = "参数不全！";
            result_code = "6666";
        }
        result.put("message", message);
        result.put("result_code", result_code);
        LogCvt.info(result.toString());
        return result;
    }

    /**
     * 5.25 产品标引结果导出记录查询
     *
     * @param reqVo
     * @return
     */
    @RequestMapping(value = "/ExportIndexingList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> ExportIndexingList(@RequestBody GetIndexingExportReqVoWsd reqVo) {
        LogCvt.info("/Service/ExportIndexingList");
        Map<String, Object> result = new HashMap<>();
        String message = "操作失败";
        String result_code = "9999";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        GetIndexingExportReqVo vo = null;
        Date startTime = null;
        Date endTime = null;
        if (null != reqVo) {
            System.out.println(reqVo.toString());
            try {
                if (reqVo.getStartTime() != null) {
                    startTime = df.parse(reqVo.getStartTime());
                }
                if (reqVo.getEndTime() != null) {
                    endTime = df.parse(reqVo.getEndTime());
                }
                vo = new GetIndexingExportReqVo(reqVo.getProductName(), reqVo.getThemeTableId(),
                        reqVo.getThemeTableName(), reqVo.getPathCode(), reqVo.getExportType(),
                        reqVo.getCreateBy(), startTime, endTime);
                List<GetIndexingExportResVo> list = idxExportIndexingProductService.getExportIndexingList(vo);
                message = "操作成功！";
                result_code = "0000";
                result.put("length", list.size());
                result.put("data", list);

            } catch (Exception ex) {
                if (ex instanceof ParseException) {
                    message = "日期格式有误！";
                } else {
                    message = ex.getMessage();
                }
                LogCvt.error("产品标引结果导出记录查询失败，原因：" + ex.getMessage());
                logs = ProgramLogsCommon.init();
                logs.setMessage("/Service/ExportIndexingList");
                logs.setLevel("1");
                logs.setLogger("ToDataBase");
                logs.setLogTime(DateUtil.parseFormatToDate(DateUtil.getCurTotalDate()));
                logs.setException(ex.toString());
                logsService.insertSelective(logs);

                message = "操作失败：" + message;
            }
        } else {
            message = "参数不全！";
            result_code = "6666";
        }
        result.put("message", message);
        result.put("result_code", result_code);
        LogCvt.info(result.toString());
        return result;
    }

    /**
     * 5.26 产品标引导出历史记录删除
     *
     * @param reqVo
     * @return
     */
    @RequestMapping(value = "/DeleteExportIndexing", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> deleteExportIndexing(@RequestBody DelExportThemeWordsReqVo reqVo) {
        LogCvt.info("/Service/DeleteExportIndexing");
        Map<String, Object> result = new HashMap<>();
        String message = "操作失败";
        String result_code = "9999";
        if (null != reqVo && reqVo.getIds() != null && reqVo.getIds().size() > 0) {
            System.out.println(reqVo.toString());
            try {
                int count = idxExportIndexingProductService.selectCountByKeys(reqVo.getIds());
                if (count < reqVo.getIds().size()) {
                    count = reqVo.getIds().size() - count;
                    message = "有" + count + "条记录不存在或者重复,无法删除！";
                } else {
                    for (String id : reqVo.getIds()) {
                        //删除数据库的一条记录
                        idxExportIndexingProductService.deleteByPrimaryKey(id);
                    }
                    //idxThemeTableService.export(reqVo, );
                    message = "操作成功！";
                    result_code = "0000";
                }
            } catch (Exception ex) {
                LogCvt.error("产品标引导出历史记录删除失败，原因：" + ex.getMessage());
                logs = ProgramLogsCommon.init();
                logs.setMessage("/Service/DeleteExportIndexing");
                logs.setLevel("1");
                logs.setLogger("ToDataBase");
                logs.setLogTime(DateUtil.parseFormatToDate(DateUtil.getCurTotalDate()));
                logs.setException(ex.toString());
                logsService.insertSelective(logs);

                message = "操作失败：" + ex.getMessage();
            }
        } else {
            message = "参数不全！";
            result_code = "6666";
        }


        result.put("message", message);
        result.put("result_code", result_code);
        LogCvt.info(result.toString());
        return result;
    }

    /**
     * 5.27 产品标引主题词表审核
     *
     * @param reqVo
     * @return
     */
    @RequestMapping(value = "/innertext/auditProductThemeTable", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> auditProductThemeTable(@RequestBody ProductThemeTableAuditReqVo reqVo) {
        LogCvt.info("/Service/innertext/auditProductThemeTable");
        Map<String, Object> result = new HashMap<>();
        String message = "操作失败";
        String result_code = "9999";
        if (null != reqVo && reqVo.isNotBlank()) {
            LogCvt.info(reqVo.toString());
            try {
                //构造实体对象，设置参数
                if (reqVo.getCheckStatus() != 0 && reqVo.getCheckStatus() != -1) {
                    message = "状态参数不合法！";
                } else {
                    IdxIndexingProductsCheck idxIndexingProductsCheck = new IdxIndexingProductsCheck();
                    idxIndexingProductsCheck.setCheckId(UUID.randomUUID().toString().toLowerCase().replaceAll("-", ""));
                    idxIndexingProductsCheck.setTaskId(reqVo.getTaskId());
                    idxIndexingProductsCheck.setProductId(reqVo.getProductId());
                    idxIndexingProductsCheck.setThemeTableId(reqVo.getThemeTableId());
                    idxIndexingProductsCheck.setCheckStatus(reqVo.getCheckStatus());
                    idxIndexingProductsCheck.setCreateBy(reqVo.getUsername());
                    idxIndexingProductsCheck.setCreateTime(new Date());
                    idxIndexingProductsCheckService.insertSelective(idxIndexingProductsCheck);
                    LogCvt.info(idxIndexingProductsCheck.toString());
                    message = "操作成功！";
                    result_code = "0000";
                }
            } catch (Exception ex) {
                LogCvt.error("产品标引主题词表审核失败，原因：" + ex.getMessage());
                logs = ProgramLogsCommon.init();
                logs.setMessage("/Service/auditProductThemeTable");
                logs.setLevel("1");
                logs.setLogger("ToDataBase");
                logs.setLogTime(DateUtil.parseFormatToDate(DateUtil.getCurTotalDate()));
                logs.setException(ex.toString());
                logsService.insertSelective(logs);

                message = "操作失败：" + ex.getMessage();
            }
        } else {
            message = "参数不全！";
            result_code = "6666";
        }

        result.put("message", message);
        result.put("result_code", result_code);
        LogCvt.info(result.toString());
        return result;
    }

    /**
     * 5.28 产品标引主题词表列表
     *
     * @param reqVo
     * @return
     */
    @RequestMapping(value = "/innertext/getProductThemeTableList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getProductThemeTableList(@RequestBody ProductThemeTableReqVo reqVo) {
        LogCvt.info("/Service/innertext/getProductThemeTableList");
        Map<String, Object> result = new HashMap<>();
        String message = "操作失败";
        String result_code = "9999";
        if (null != reqVo) {
            LogCvt.info(reqVo.toString());
            try {
                //获取分页结果列表
                PagedResult<ProductThemeTableResVo> pagedResult = idxIndexingProductsCheckService.getProductThemeTableList(reqVo);
                //idxThemeTableService.export(reqVo, );
                List<ProductThemeTableResVo> data = pagedResult.getDataList();
                result.put("length", pagedResult.getTotal());
                result.put("data", data);
                message = "操作成功！";
                result_code = "0000";
            } catch (Exception ex) {
                LogCvt.error("产品标引主题词表查询失败，原因：" + ex.getMessage());
                logs = ProgramLogsCommon.init();
                logs.setMessage("/Service/innertext/getProductThemeTableList");
                logs.setLevel("1");
                logs.setLogger("ToDataBase");
                logs.setLogTime(DateUtil.parseFormatToDate(DateUtil.getCurTotalDate()));
                logs.setException(ex.toString());
                logsService.insertSelective(logs);

                message = "操作失败：" + ex.getMessage();
            }
        } else {
            message = "参数不全！";
            result_code = "6666";
        }

        result.put("message", message);
        result.put("result_code", result_code);
        LogCvt.info(result.toString());
        return result;
    }

    /**
     * 5.29 产品参考标引列表 OK
     *
     * @param reqVo
     * @return
     */
    @RequestMapping(value = "/innertext/getRefIndexingList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getRefIndexingList(@RequestBody RefIndexingReqVo reqVo) {
        LogCvt.info("/Service/innertext/getRefIndexingList");
        Map<String, Object> result = new HashMap<>();
        String message = "操作失败";
        String result_code = "9999";
        if (null != reqVo && reqVo.getTaskId() != null) {
            LogCvt.info(reqVo.toString());
            try {
                if (idxTaskService.selectByPrimaryKey(reqVo.getTaskId()) == null) {
                    message = "该任务不存在！";
                } else {
                    //获取分页结果列表
                    PagedResult<RefIndexingResVo> pagedResult = idxTaskProductService.getRefIndexingList(reqVo);
                    //idxThemeTableService.export(reqVo, );
                    List<RefIndexingResVo> data = pagedResult.getDataList();
                    result.put("length", pagedResult.getTotal());
                    result.put("data", data);
                    message = "操作成功！";
                    result_code = "0000";
                }
            } catch (Exception ex) {
                LogCvt.error("产品参考标引列表查询失败，原因：" + ex.getMessage());
                logs = ProgramLogsCommon.init();
                logs.setMessage("/Service/innertext/getRefIndexingList");
                logs.setLevel("1");
                logs.setLogger("ToDataBase");
                logs.setLogTime(DateUtil.parseFormatToDate(DateUtil.getCurTotalDate()));
                logs.setException(ex.toString());
                logsService.insertSelective(logs);

                message = "操作失败：" + ex.getMessage();
            }
        } else {
            message = "参数不全！";
            result_code = "6666";
        }

        result.put("message", message);
        result.put("result_code", result_code);
        LogCvt.info(result.toString());
        return result;
    }

}
